package com.ipzoe.common.service;

import com.ipzoe.common.bean.entity.AdminMenu;
import com.ipzoe.common.repository.AdminMenuRepository;
import com.ipzoe.common.util.DefaultService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单Service
 * <p>
 * Created 2018/01/19.
 *
 * @author pfzhang
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class AdminMenuService extends DefaultService<AdminMenu> {

    private AdminMenuRepository adminMenuRepository;

    @Resource
    public void setAdminMenuRepository(AdminMenuRepository adminMenuRepository) {
        this.adminMenuRepository = adminMenuRepository;
        super.setDefaultMapper(adminMenuRepository);
    }

    /**
     * 根据level组织后台管理菜单并且去除首页管理.(获取除首页外的所有菜单)
     * <p>
     * 注意: 表中level必须连续.
     *
     * @param level 0表示顶级主菜单, 数字增加, 为各级子菜单.
     * @return 菜单列表
     */
    public List<AdminMenu> generateAdminMenuByFilter(Integer level, Long father) {
        List<AdminMenu> menus = adminMenuRepository.findByLevelAndFather(level, father);
        for (AdminMenu menu : menus) {
            menu.setSubMenu(generateAdminMenuByFilter(level + 1, menu.getId()));
        }

        return menus;
    }

    /**
     * 根据level组织后台管理菜单.(获取该角色下的菜单)
     * <p>
     * 注意: 表中level必须连续.
     *
     * @param roleId 角色ID
     * @param level  0表示顶级主菜单, 数字增加, 为各级子菜单.
     * @param father 父菜单ID
     * @return 菜单列表
     */
    public List<AdminMenu> generateAdminMenu(Long roleId, Integer level, Long father) {
        List<AdminMenu> menus = adminMenuRepository.findByUserIdAndLevelAndFather(roleId, level, father);
        for (AdminMenu menu : menus) {
            menu.setSubMenu(generateAdminMenu(roleId, level + 1, menu.getId()));
        }
        return menus;
    }

    /**
     * 获取所有的菜单集合,不包含首页
     *
     * @return 菜单集合
     */
    public List<AdminMenu> selectAllNotIndex() {
        return adminMenuRepository.selectAllNotIndex();
    }
}
